package com.zds.support.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.UiModeManager;
import android.bluetooth.BluetoothAdapter;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.location.LocationManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.webkit.WebSettings;
import android.widget.Toast;


import java.security.MessageDigest;
import java.util.List;
import java.util.UUID;

public class AppUtils {
    public static Context appContext;
    public static boolean isDebug = false;
    public static boolean isHasCheckAppVersion = false;
    public static boolean isHasPlan = false;
    private static int activityCount = 0;

    public static void addActivityCount() {
        activityCount++;
    }

    public static void reduceActivityCount() {
        activityCount--;
    }

    public static boolean isAppInForeground() {
        return activityCount > 0;
    }

    private static Handler sHandler = new Handler(Looper.getMainLooper());

    /**
     * 是否是主进程
     */
    public static boolean isMainProcess(Context context) {
        String procName = getCurrentProcessName(context);
        return procName == null || procName.equalsIgnoreCase(context.getPackageName());
    }

    /**
     * 获取当前进程名字
     */
    public static String getCurrentProcessName(Context context) {
        int pid = Process.myPid();
        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    public static void restartApplication(Context context) {
        final Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

    /**
     * 调用系统分享
     */
    public static void shareToOtherApp(Context context, String title, String content, String dialogTitle) {
        Intent intentItem = new Intent(Intent.ACTION_SEND);
        intentItem.setType("text/plain");
        intentItem.putExtra(Intent.EXTRA_SUBJECT, title);
        intentItem.putExtra(Intent.EXTRA_TEXT, content);
        intentItem.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(Intent.createChooser(intentItem, dialogTitle));
    }

    /**
     * need < uses-permission android:name =”android.permission.GET_TASKS” />
     * 判断是否前台运行
     */
    public static boolean isRunningForeground(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> taskList = am.getRunningTasks(1);
        if (taskList != null && !taskList.isEmpty()) {
            ComponentName componentName = taskList.get(0).topActivity;
            if (componentName != null && componentName.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取App包 信息版本号
     */
    public PackageInfo getPackageInfo(Context context) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo = null;
        try {
            packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return packageInfo;
    }

    /**
     * 获取app版本名称
     *
     * @return 获取失败返回""，否则返回版本名称
     */
    public static String getVersionName() {
        String versionName = "";
        if (appContext == null)
            return versionName;
        try {
            PackageManager pm = appContext
                    .getPackageManager();
            PackageInfo pi = pm.getPackageInfo(appContext.getPackageName(), 0);
            versionName = pi.versionName;
            if (TextUtils.isEmpty(versionName)) {
                return "";
            }
        } catch (Exception e) {
        }
        return versionName;
    }

    /**
     * 获取app版本号
     *
     * @return 获取失败返回-1，否则返回版本号
     */
    public static int getVersionCode() {
        int versionCode = -1;
        if (appContext == null)
            return versionCode;
        try {
            PackageManager pm = appContext
                    .getPackageManager();
            PackageInfo pi = pm.getPackageInfo(appContext.getPackageName(), 0);
            versionCode = pi.versionCode;
        } catch (Exception e) {
        }
        return versionCode;
    }

    public static String getDeviceId() {
        String deviceId = PreferenceUtils.getString(AppUtils.appContext,
                "sp_yse", "key_device_id", "");
        if (TextUtils.isEmpty(deviceId)) {
            String uuid = UUID.randomUUID().toString().replace("-", "");
            PreferenceUtils.putString(AppUtils.appContext, "sp_yse", "key_device_id", uuid);
            deviceId = uuid;
        }
        return deviceId;
    }

    public static String getImei(Context context) {
        String imei = "";
        try {
            imei = getPhoneImei(context);
        } catch (Exception e) {

        }
        if (TextUtils.isEmpty(imei)) {
            String macIdP = PreferenceUtils.getString(context, "sp_app_uuid", "key_mac_uuid", "");
            if (TextUtils.isEmpty(macIdP)) {
                String uuid = UUID.randomUUID().toString().replace("-", "");
                PreferenceUtils.putString(context, "sp_app_uuid", "key_mac_uuid", uuid);
                imei = uuid;
            } else {
                imei = macIdP;
            }
        }
        return imei;
    }

    @SuppressWarnings("all")
    private static String getPhoneImei(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (tm != null) {
            return tm.getDeviceId();
        }
        return "";
    }

    public static void killTheApp() {
        Process.killProcess(Process.myPid());
        System.exit(0);
    }

    public static void openBlueTooth(Activity activity, int requestCode) {
        try {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            activity.startActivityForResult(enableBtIntent, requestCode);
        } catch (Exception e) {
            Toast.makeText(activity, "打开蓝牙失败，请到系统设置页面打开。", Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 手机是否开启位置服务，如果没有开启那么所有app将不能使用定位功能
     */
    public static boolean isLocServiceEnable(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null) {
            return false;
        }
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }

    public static void openLocSetting(Activity activity) {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            activity.startActivity(intent);
        } catch (ActivityNotFoundException ex) {
            //如果页面无法打开，进入设置页面
            intent.setAction(Settings.ACTION_SETTINGS);
            try {
                activity.startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public static String encrypt(String str) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        char[] charArray = str.toCharArray();
        byte[] byteArray = new byte[charArray.length];
        for (int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte) charArray[i];
        }
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    public static void openBlueToothSettingUI(Activity activity) {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_BLUETOOTH_SETTINGS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            activity.startActivity(intent);
        } catch (ActivityNotFoundException ex) {
            ex.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static boolean isUIThread() {
        return Looper.myLooper() == Looper.getMainLooper();
    }

    public static void runOnUI(Runnable r) {
        sHandler.post(r);
    }



    public static boolean isAppInstalled(Context context, String packname) {
        PackageInfo packageInfo = null;

        try {
            packageInfo = context.getPackageManager().getPackageInfo(packname, 0);
        } catch (PackageManager.NameNotFoundException var4) {
            packageInfo = null;
        }

        return packageInfo != null;
    }

    /**
     * 判断当前设备是手机还是平板，代码来自 Google I/O App for Android
     *
     * @param context
     * @return 平板返回 True，手机返回 False
     */
    public static boolean isPad(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    /**
     * 判断当前是否TV
     *
     * @param context
     * @return TV True，手机返回 False
     */
    public static boolean isTv(Context context) {
        UiModeManager uiModeManager = (UiModeManager) context.getSystemService(Context.UI_MODE_SERVICE);
        if (uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION) {
            return true;
        } else {
            return false;
        }
    }


    public static boolean getIsDebugMode(Context context, Boolean defaultValue) {
        return PreferenceUtils.getBoolean(context, "key_is_debug_mode", defaultValue);
    }

    public static void setIsDebugMode(Context context, Boolean isDebugMode) {
        PreferenceUtils.putBoolean(context, "key_is_debug_mode", isDebugMode);
    }

    public static String getUserAgent() {
        String userAgent = "";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            try {
                userAgent = WebSettings.getDefaultUserAgent(appContext);
            } catch (Exception e) {
                userAgent = System.getProperty("http.agent");
            }
        } else {
            userAgent = System.getProperty("http.agent");
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0, length = userAgent.length(); i < length; i++) {
            char c = userAgent.charAt(i);
            if (c <= '\u001f' || c >= '\u007f') {
                sb.append(String.format("\\u%04x", (int) c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
    public static void reboot() {
//        new Thread() {
//            @Override
//            public void run() {
//                super.run();
//                try {
//
//                    CommandResult result = Shell.SH.run("reboot");
//                    if (result.isSuccessful()) {
//                        LogUtils.d("命令行", "执行成功 :" + result.getStdout().toString());
//                    } else {
//                        LogUtils.d("命令行", "执行失败 " + result.stderr.toString());
//                    }
//
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    LogUtils.d("命令行", "执行error : " + e.getLocalizedMessage());
//                }
//            }
//        }.run();
    }
    public static void restartAppForInstall(Context context) {
        try {
           // Toast.makeText(context, "即将重启APP", Toast.LENGTH_SHORT).show();
            reboot();
            //check if the context is given
            if (context != null) {
                //fetch the packagemanager so we can get the default launch activity
                // (you can replace this intent with any other activity if you want
                PackageManager pm = context.getPackageManager();
                //check if we got the PackageManager
                if (pm != null) {
                    //create the intent with the default start activity for your application
                    Intent mStartActivity = pm.getLaunchIntentForPackage(
                            context.getPackageName()
                    );
                    if (mStartActivity != null) {
                        mStartActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        //create a pending intent so the application is restarted after System.exit(0) was called.
                        // We use an AlarmManager to call this intent in 100ms
                        int mPendingIntentId = 223344;
                        PendingIntent mPendingIntent = PendingIntent
                                .getActivity(context, mPendingIntentId, mStartActivity,
                                        PendingIntent.FLAG_CANCEL_CURRENT);
                        AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
                        //kill the application
                        System.exit(0);
                    } else {
                        LogUtils.d("SplashActivity  ---> do restart  Was not able to restart application, mStartActivity null");
                    }
                } else {
                    LogUtils.d("SplashActivity  ---> do restart Was not able to restart application, PM null");
                }
            } else {
                LogUtils.d("SplashActivity  ---> do restart Was not able to restart application, Context null");
            }
        } catch (Exception ex) {
            LogUtils.d("SplashActivity  ---> do restart  Was not able to restart application " + ex.getLocalizedMessage());
        }
        try {
            System.exit(0);
            Process.killProcess(Process.myPid());
        } catch (Exception e) {

        }
    }
    // 用户链路 埋点
    // 1. 我的计划 2. 目标选择   3. 水平选择  4. 标签 5. 私人计划  6. 新计划
    // 7. 首页课程推荐 8. 首页日推好课 9. 课程列表 10. 节目单 11. 让我们开始骑行 12.猜你喜欢
    public static int getCourseSource(Context context) {
        return PreferenceUtils.getInt(context, "key_course_source", 0);
    }

    public static void setCourseSource(Context context, int source) {
        PreferenceUtils.putInt(context, "key_course_source", source);
    }
}
